package com.lijunyan.blackmusic.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.lijunyan.blackmusic.R;
import com.lijunyan.blackmusic.database.DBUserInfoLogin;
import com.lijunyan.blackmusic.entity.UserInfo;
import com.lijunyan.blackmusic.eventbus.LoginStateEventBus;
import com.lijunyan.blackmusic.util.MyApplication;
import com.lijunyan.blackmusic.util.MyMusicUtil;
import com.lijunyan.blackmusic.util.ToastUtil;
import com.lijunyan.blackmusic.view.EmailAutoCompleteTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/*
 * path: RestaurantDemo
 * Author: 86133
 * Create: 2019/12/3 11:35
 * Changes (from 2019/12/3)
 * Desc:
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back;

    private TextView title;
    //注册按钮
    private TextView register;

    private EmailAutoCompleteTextView login_user_name;

    private EditText login_user_password;

    private TextView login;

    //用户名、手机号、邮箱
    private String username;
    //密码
    private String password;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
        prepare();
        initView();
        setListener();
    }

    private void prepare() {
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);

        title = (TextView) findViewById(R.id.title);
        title.setText("登录");
        title.setVisibility(View.VISIBLE);

        register = (TextView) findViewById(R.id.function);
        register.setText("注册");
        register.setVisibility(View.VISIBLE);
//        register.setTextColor(Color.parseColor("#AE7654"));

        login_user_name = (EmailAutoCompleteTextView) findViewById(R.id.login_user_name);
        login_user_password = (EditText) findViewById(R.id.login_user_password);
        login = (TextView) findViewById(R.id.login);

        initTheme();
    }


    private void initTheme(){
        int themeId = MyMusicUtil.getTheme(LoginActivity.this);
        switch (themeId){
            default:
            case 0:
                login.setBackgroundResource(R.color.biliPink);
                break;
            case 1:
                login.setBackgroundResource(R.color.zhihuBlue);
                break;
            case 2:
                login.setBackgroundResource(R.color.kuanGreen);
                break;
            case 3:
                login.setBackgroundResource(R.color.cloudRed);
                break;
            case 4:
                login.setBackgroundResource(R.color.tengluoPurple);
                break;
            case 5:
                login.setBackgroundResource(R.color.seaBlue);
                break;
            case 6:
                login.setBackgroundResource(R.color.grassGreen);
                break;
            case 7:
                login.setBackgroundResource(R.color.coffeeBrown);
                break;
            case 8:
                login.setBackgroundResource(R.color.lemonOrange);
                break;
            case 9:
                login.setBackgroundResource(R.color.startSkyGray);
                break;
            case 10:
                login.setBackgroundResource(R.color.nightActionbar);
                break;
        }
    }


    private void setListener() {
        back.setOnClickListener(this);
        register.setOnClickListener(this);
        login.setOnClickListener(this);
    }

    /**
     * @Desc:  发送登录信息
     * @Author:  86133
     * @Time:  2019/6/21 16:15
     */
    private void postLoginData(){
        username = login_user_name.getText().toString().trim();
        if(TextUtils.isEmpty(username)){
            ToastUtil.showToast("请输入用户名");
            return;
        }
        password = login_user_password.getText().toString().trim();
        if(TextUtils.isEmpty(password)){
            ToastUtil.showToast("请输入密码");
            return;
        }

        ArrayList<UserInfo> userInfos = DBUserInfoLogin.queryUserInfoList(username);
        boolean flag = false;
        if(userInfos!=null && userInfos.size()>0){
            for (int i = 0; i < userInfos.size(); i++) {
                UserInfo userInfo = userInfos.get(i);
                if(userInfo!=null){
                    String userName = userInfo.getUserName();
                    String userPassword = userInfo.getUserPassword();
                    if(!TextUtils.isEmpty(userName)&&userName.equals(this.username)&&!TextUtils.isEmpty(userPassword)&&userPassword.equals(this.password)){
                        saveUserName(userName);
                        flag = true;
                        ToastUtil.showToast("登录成功");
                        EventBus.getDefault().post(new LoginStateEventBus(true,userInfo));
                        finish();
                        break;
                    }
                }
            }
        }else{
            flag = true;
            ToastUtil.showToast("未查找到该用户");
        }
        if(!flag){
            ToastUtil.showToast("用户名或密码错误");
        }
    }

    /**
     * @Desc:  保存用户信息
     * @Author:  86133
     * @Time:
     */
    private void saveUserName(String userName) {
        SharedPreferences spf = MyApplication.getContext().getSharedPreferences("SP_LOGIN_NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = spf.edit();
        if(!TextUtils.isEmpty(userName)){
            editor.putString("userName", userName);
        }
        editor.commit();
    }

    @Override
    protected void onPause() {
        super.onPause();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = LoginActivity.this.getCurrentFocus();
        if (null != imm && view!=null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.function:
                RegisterActivity.startRegisterActivity(this);
                break;
            case R.id.login:
                postLoginData();
                break;
        }
    }

    /**
     * @param context
     * @param
     */
    public static void startLoginActivity(Context context) {
        if (context != null) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginStateEventBus(LoginStateEventBus loginState){
        if(loginState!=null){
            Intent intent = new Intent();
            intent.setClass(this, HomeActivity.class);
            startActivity(intent);
            finish();
        }
    }
}
